package com.wxs.common.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wxs.common.dao.RoleMapper;
import com.wxs.common.pojo.Role;
import com.wxs.common.service.RoleService;
import com.wxs.common.utils.DataGridModel;
import com.wxs.common.utils.DataResult;

/**
 * 角色
 * 
 * @author admin
 *
 */
@Service
public class RoleServiceImpl implements RoleService {
	@Autowired
	private RoleMapper roleMapper;

	@Override
	public List<Role> queryForList(Integer roleGroupId) {
		return roleMapper.listRolesByGroupid(roleGroupId);
	}

	@Override
	public DataResult queryPage(String name, Boolean enabled, DataGridModel dgm) {
		PageHelper.startPage(dgm.getPage(), dgm.getLimit());
		List<Role> ls = roleMapper.list(name, enabled);
		PageInfo<Role> result = new PageInfo<Role>(ls);
		return new DataResult(ls, result.getTotal());
	}

	@Override
	public List<Role> findAllByEnabled(Boolean enabled) {
		return roleMapper.list(null, enabled);
	}

	@Override
	public Role findById(Integer id) {
		return roleMapper.selectByPrimaryKey(id);
	}

	@Override
	public int editRole(Role role) {
		return roleMapper.updateByPrimaryKeySelective(role);
	}

	@Override
	public boolean checkName(String name, Integer id) {
		List<Role> roles = roleMapper.list(name, null);
		if (roles == null || roles.isEmpty()) {
			return false;
		} else {
			Role role = roles.get(0);
			if (id == null) {
				return true;
			} else if (role.getId().equals(Integer.valueOf(id))) {
				return false;
			} else {
				return true;
			}
		}
	}

	@Override
	public int deleteById(Integer id) {
		roleMapper.deleteRole_Resource(id);
		roleMapper.deleteRolegroup_Role(id);
		return roleMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int saveRole(Role role) {
		return roleMapper.insertSelective(role);
	}

	@Override
	public int saveRoleResource(String[] resourceids, Integer roleid) {
		roleMapper.deleteRole_Resource(roleid);
		if (resourceids.length > 0)
			return roleMapper.saveRoleResource(resourceids, roleid);
		return 0;
	}

}
